from django.db import models


class User(models.Model):
    username = models.CharField(max_length=8, unique=True, verbose_name='用户名')
    password = models.CharField(verbose_name='密码')
    gold = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, verbose_name='口袋币')

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = '用户'


class Product(models.Model):
    name = models.CharField(max_length=50, verbose_name='商品名称', unique=True)
    appearance = models.JSONField(default=dict, verbose_name="商品外观")

    price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='价格')
    description = models.TextField(max_length=100, verbose_name='商品描述', null=False)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='上架时间')
    expires_at = models.DateTimeField(verbose_name='过期时间')
    sold = models.BooleanField(default=False, verbose_name='是否已售出')
    owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='商品创始人', related_name='products')

    def __str__(self):
        return f"{self.owner} 制造了 {self.name}"

    class Meta:
        verbose_name = '商品'


class Transaction(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='商品')    
    buyer = models.ForeignKey(User, related_name='buyer', on_delete=models.CASCADE, verbose_name='买家')
    seller = models.ForeignKey(User, related_name='seller', on_delete=models.CASCADE, verbose_name='卖家')
    price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='交易价格')
    transaction_at = models.DateTimeField(auto_now_add=True, verbose_name='交易时间')

    def __str__(self):
        return f"{self.buyer.username} bought {self.product.name} from {self.seller.username}"

    class Meta:
        verbose_name = '交易订单'


class Checkin(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    checkin_date = models.DateField(auto_now_add=True, verbose_name='签到日期')
    day = models.IntegerField(default=0, verbose_name='签到天数')
    reward = models.DecimalField(max_digits=8, decimal_places=2, default=0.00, verbose_name='签到奖励')

    def __str__(self):
        return f"{self.user.username} checked in on {self.checkin_date}"

    class Meta:
        verbose_name = '签到记录'